/**
 * Created by Ding on 2016/4/8.
 * Copyright (c) 2016, auais.com All Rights Reserved.
 * File Name:
 * Package Name:
 * Date:2016/4/8 11:23
 */
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb');
//const GridStore = require('mongodb').GridStore;
const GridFSBucket = require('mongodb').GridFSBucket;
const fs = require("fs");
const path = require('path');
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const crypto = require('crypto');

module.exports = {
    open:true,
    handler: (req, res, next)=>{
        req.context=req.context||{};
        console.log('req.context:::',req.context.authInfo);
        const authInfo = req.context.authInfo||{};
        const fsHash = crypto.createHash('md5');
        let filesize = 0;

        const busboy = new Busboy({headers: req.headers});
        req.pipe(busboy);
        busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
            const id = new ObjectID();

            let extName = path.extname(filename);
            let fileName = req.query.fileName || filename;
            if(!path.extname(fileName)||path.extname(fileName)!== extName)
                fileName = fileName + extName;
            let localPath = '/static/';
            let saveTo = path.join('.'+localPath, '', fileName);
            file.pipe(fs.createWriteStream(saveTo));

            file.on('end', function () {
                //console.log("end");
                const url = req.config.sys.resHost+ localPath +  fileName;
                const fileObj = {
                    _id: id,
                    filename: filename,
                    content_type: mimetype,
                    filesize: filesize,
                    url: url,
                    createTime:new Date(),
                    userId:authInfo._id,
                    userName:authInfo.name,
                    static:1,
                    md5:  fsHash.digest('hex')
                };
                res.json(fileObj);
                //将资源记录用户表
                let fn = function () {
                };
                req.mongo.collection("file").insertOne(fileObj,fn);

            }).on('error', function (err) {
                console.log("err:" + err)
            }).on('data', function (data) {
                filesize += data.length;
                fsHash.update(data);
            });

        })
    }
};